<template>
  <div v-loading="loading">
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_salesorder'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >供应商年度评审</span
            >
          </div>
          <div
            class="inline-block text-15px ml-10px"
            style="vertical-align: bottom"
            v-if="bpmnStatus"
          >
            <i
              :class="
                bpmnStatus == '审批通过'
                  ? 'h-8px w-8px bg-#fe9400 inline-block rounded'
                  : bpmnStatus == '流程未发起'
                  ? 'h-8px w-8px bg-#ccc inline-block rounded'
                  : 'h-8px w-8px bg-#10d070 inline-block rounded'
              "
            ></i>
            {{ bpmnStatus }}
          </div>
        </div>
        <div class="text-right">
          <slot></slot>
          <el-button
            type="primary"
            plain
            @click="handleSubmit('examine')"
            v-if="isExamine && isCanStart"
            >发起申请</el-button
          >
          <el-button
            type="primary"
            @click="handleSubmit('save')"
            v-if="!formDisabled"
            >保存</el-button
          >
          <!-- <el-button @click="handleReset(form)" v-if="isCanStart"
            >重置</el-button
          > -->
          <el-button type="primary" plain @click="handleReturn">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container form-box">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        :disabled="formDisabled"
        label-width="150px"
      >
        <el-collapse v-model="activeNames">
          <!-- 基本信息 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="基础信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="年度" prop="annual">
                  <el-date-picker
                    class="w-full"
                    v-model="formData.annual"
                    type="year"
                    format="YYYY"
                    value-format="YYYY"
                    placeholder="请输入年度"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input
                    disabled
                    v-model="formData.supplierName"
                    placeholder="请输入供应商名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业税号" prop="supplierTaxcode">
                  <el-input
                    disabled
                    v-model="formData.supplierTaxcode"
                    placeholder="请输入企业税号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商地址" prop="address">
                  <el-input
                    v-model="formData.address"
                    placeholder="请输入供应商地址"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="合作事项" prop="cooperationMatters">
                  <el-input
                    v-model="formData.cooperationMatters"
                    placeholder="请输入合作事项"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="供应产品/服务" prop="supplierProduct">
                  <el-input
                    v-model="formData.supplierProduct"
                    placeholder="请输入供应产品/服务"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactName">
                  <el-input
                    v-model="formData.contactName"
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input
                    v-model="formData.contactPhone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="供应商类别" prop="supplierType">
                  <el-radio-group v-model="formData.supplierType">
                    <el-radio
                      v-for="item in evaluate_supplier_type"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type == '3'">
                <el-form-item label="开户银行" prop="depositBank">
                  <el-input
                    v-model="formData.depositBank"
                    placeholder="请输入开户银行"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type == '3'">
                <el-form-item label="银行账号" prop="bankAccount">
                  <el-input
                    v-model="formData.bankAccount"
                    placeholder="请输入银行账号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type == '3'">
                <el-form-item label="联行号" prop="interbankNumber">
                  <el-input
                    v-model="formData.interbankNumber"
                    placeholder="请输入联行号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type == '3'">
                <el-form-item label="支付说明" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    placeholder="请输入支付说明"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件" prop="supplierEvaluateFileList">
                  <template #label="{ label }">
                    <div class="text-right">
                      {{ label }}
                    </div>
                    <el-popover
                      placement="top-start"
                      title="注意"
                      width="50%"
                      trigger="hover"
                    >
                      <template #reference>
                        <el-icon><QuestionFilled /></el-icon>
                      </template>
                      <div>
                        <p>信用、供方资料（授权资质、最新营业执照等）</p>
                      </div>
                    </el-popover>
                  </template>
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="
                      file =>
                        beforeAvatarUpload(file, 'supplierEvaluateFileList')
                    "
                    :http-request="
                      params => requestFile(params, 'supplierEvaluateFileList')
                    "
                    :accept="uploadType['contract'].toString()"
                    :limit="10"
                    :show-file-list="false"
                  >
                    <!--
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt, .pptx,.gif, .jpg, .jpeg, .png" -->
                    <el-button type="default" style="font-size: 14px"
                      ><el-icon><UploadFilled /></el-icon>上传</el-button
                    >
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        {{
                          `支持格式${uploadType[
                            'contract'
                          ].toString()} ，单个文件不能超过20MB`
                        }}
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div
                      v-for="(item, index) in formData.supplierEvaluateFileList"
                      :key="item.fileName"
                    >
                      <el-link
                        @click="viewFiles(item.url)"
                        :underline="false"
                        type="primary"
                        >{{ item.origFileName }}</el-link
                      >
                      <el-button
                        text
                        plain
                        @click="delFileName(index, 'supplierEvaluateFileList')"
                        >删除</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 年度评价内容（可根据实际合作情况调整） -->
          <el-collapse-item name="2" disabled v-if="formData.type != '3'">
            <template #title>
              <TitleName
                title="年度评价内容（可根据实际合作情况调整）"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-table
              :data="tableData"
              :span-method="objectSpanMethod"
              border
              :summary-method="getSummaries"
              show-summary
              class="mt-20px"
            >
              <el-table-column prop="colOne" label="评价指标" min-width="25%" />
              <el-table-column
                prop="colTwo"
                label="各指标项下具体评价条款解释"
                min-width="45%"
              >
                <template #default="scope">
                  <div class="text-14px" v-if="scope.row.colTwoField">
                    <el-form-item
                      :label="scope.row.colTwo"
                      :prop="scope.row.colTwoField"
                      v-if="scope.row.colTwoField"
                      label-width="50%"
                    >
                      <el-input
                        v-model="formData[scope.row.colTwoField]"
                        :placeholder="`请输入${scope.row.colTwo}`"
                      />
                    </el-form-item>
                  </div>
                  <div v-else>
                    {{ scope.row.colTwo }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="参考分值" min-width="10%" />
              <el-table-column label="评价分值" min-width="20%">
                <template #default="scope">
                  <el-form-item
                    :prop="scope.row.scoreField"
                    v-if="scope.row.scoreField"
                    label-width="0"
                  >
                    <el-input-number
                      class="w-full"
                      v-model="formData[scope.row.scoreField]"
                      :step="1"
                      :placeholder="
                        scope.row.id == '6'
                          ? `请输入${scope.row.colTwo}得分`
                          : `请输入${scope.row.colOne}得分`
                      "
                      :max="scope.row.scoreMax"
                      :min="scope.row.scoreMin"
                      :precision="0"
                      :controls="false"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <!-- 等级评定标准 -->
          <el-collapse-item name="3" disabled v-if="formData.type != '3'">
            <template #title>
              <TitleName
                title="等级评定标准"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="24" class="tatle-box">
                <table>
                  <tbody>
                    <tr>
                      <td class="w-4/24 text-center">等级划分</td>
                      <td class="w-4/24 text-center">不合格</td>
                      <td class="w-4/24 text-center">合格</td>
                      <td class="w-4/24 text-center">良好</td>
                      <td class="w-4/24 text-center">优秀</td>
                      <td class="w-4/24 text-center">等级结果</td>
                    </tr>
                    <tr>
                      <td class="text-center">等级得分要求</td>
                      <td class="text-center">≦60</td>
                      <td class="text-center">≧60</td>
                      <td class="text-center">≧80</td>
                      <td class="text-center">≧90</td>
                      <td class="text-center">{{ scoreRes }}</td>
                    </tr>
                  </tbody>
                </table>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    ></SubmissionProcess>
  </div>
</template>
<script setup name="EvaluateForm">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  setEvaluate,
  getSupplier,
  getEvaluate
} from '@/api/supplierManage/index'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { isMoneyNot, validateLen } from '@/utils/validate'
import { skipToError, viewFile, strToArr } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const props = defineProps({
  evaluateId: {
    type: [Number, String],
    require: true
  },
  id: {
    type: [Number, String],
    require: false
  }
})

const { evaluate_supplier_type } = proxy.useDict(
  'evaluate_supplier_type' //评价表中供应商类别
)
const data = reactive({
  loading: false,
  formData: {
    // deptId: userStore.userInfo.orgId,
    supplierEvaluateFileList: []
  },
  formRules: {
    annual: [
      {
        required: true,
        message: '请选择年度',
        trigger: 'blur'
      }
    ],
    supplierName: [
      {
        required: true,
        message: '请输入供应商名称',
        trigger: 'blur'
      }
    ],
    address: [
      {
        required: true,
        message: '请输入供应商地址',
        trigger: 'blur'
      }
    ],
    cooperationMatters: [
      {
        required: true,
        message: '请输入合作事项',
        trigger: 'blur'
      }
    ],
    supplierProduct: [
      {
        required: true,
        message: '请输入供应产品/服务',
        trigger: 'blur'
      }
    ],
    contactName: [
      {
        required: true,
        message: '请输入业务联系人',
        trigger: 'blur'
      }
    ],
    contactPhone: [
      {
        required: true,
        message: '请输入联系电话',
        trigger: 'blur'
      }
    ],
    supplierType: [
      {
        required: true,
        message: '请选择供应商类别',
        trigger: 'change'
      }
    ],
    supplierEvaluateFileList: [
      {
        required: true,
        message: '请上传附件',
        trigger: ['blur', 'change']
      }
    ],
    serviceCooperation: [
      {
        required: true,
        message: '请输入服务与合作',
        trigger: 'blur'
      }
    ],
    manageScore: [
      {
        required: true,
        message: '请输入经营情况',
        trigger: 'blur'
      }
    ],
    qualityScore: [
      {
        required: true,
        message: '请输入质量水平',
        trigger: 'blur'
      }
    ],
    cooperationScore: [
      {
        required: true,
        message: '请输入服务配合',
        trigger: 'blur'
      }
    ],
    serviceScore: [
      {
        required: true,
        message: '请输入其他相关要求',
        trigger: 'blur'
      }
    ],
    otherRequirementsScore: [
      {
        required: true,
        message: '请输入经营情况',
        trigger: 'blur'
      }
    ]
  },
  activeNames: ['1', '2', '3', '4', '5']
})
let { loading, formData, formRules, activeNames } = toRefs(data)

const isExamine = ref(true) // 判断是否走审批按钮
watch(
  [
    () => route.query.evaluateId,
    () => route.query.supplierData,
    () => props.evaluateId,
    () => props.id
  ],
  async val => {
    if (route.query.evaluateId && route.name == type.name) {
      getFormData(route.query.evaluateId)
    } else if (route.query.salesOrderData && route.name == type.name) {
      let salesOrderData = JSON.parse(route.query.salesOrderData)
      if (salesOrderData.id) {
        getSupplierData(salesOrderData.id)
      }
      isExamine.value = true
      // 走业务流程
      initFlowFn('29')
    } else if (props.evaluateId && route.name == 'EditEvaluate') {
      await getFormData(props.evaluateId)
      //根据业务查询审批状态
      await getBusinessProStatusFn()
      // 判断表单是否可编辑  获取当前流程节点
      let res = await getNodeData(props.evaluateId)
      bpmnStatus.value = res.data?.nowTaskName
      formDisabled.value =
        res.data == null || res.data?.isFirst == 'Y' ? false : true
    } else if (props.id && route.name == 'WorkDetail') {
      await getFormData(props.id)
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        // formDisabled.value =
        //   res.data == null || res.data?.isFirst == 'Y' ? false : true
        try {
          formDisabled.value = res.data?.formDisabled
        } catch (error) {}
        try {
          let resDis = res.data?.fieldDisabled
          fieldDisabled.value = resDis
            ? resDis.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
        try {
          let resHid = res.data?.fieldHidden
          fieldHidden.value = resHid
            ? resHid.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
      }
      formDisabled.value =
        !formDisabled.value && route.query.processed == 'true' ? false : true
      isCanStart.value = false
    }
  },
  {
    immediate: true
  }
)

// 表格信息
const tableData = ref([
  {
    id: '1',
    colOne: '1.经营情况',
    colTwo: '-营业合法性：营业执照、代理证书或代理协议等；',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: 'manageScore'
  },
  {
    id: '1',
    colOne: '1.经营情况',
    colTwo:
      '-经营规模：成立时间、注册资金、组织架构、人员规模及分布、客户群等；',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '1',
    colOne: '1.经营情况',
    colTwo: '-专业程度：技术领先，市场占有力强，品牌效应好；',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '1',
    colOne: '1.经营情况',
    colTwo: '--财务状况：财务报表、关键财务指标。',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '2',
    colOne: '2.质量水平',
    colTwo:
      '-资质认证：ISO9000、环境认证、职业健康安全认证、信息安全（隐私信息）认证、产品可靠性、知识产权证书等，有一套品质保证体系，且按照相关要求执行；',
    colTwoField: '',
    score: '20',
    scoreMax: 20,
    scoreMin: 0,
    scoreField: 'qualityScore'
  },
  {
    id: '2',
    colOne: '2.质量水平',
    colTwo:
      '-质量情况：产品检验、生产过程的满意度；产品/服务与本单位的要求以及相关技术指标的匹配程度；',
    colTwoField: '',
    score: '20',
    scoreMax: 20,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '2',
    colOne: '2.质量水平',
    colTwo: '-供应渠道：供应商所供产品的来源。',
    colTwoField: '',
    score: '20',
    scoreMax: 20,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '3',
    colOne: '3.合作情况',
    colTwo:
      '-供应周期：按约定准时或提前交付，满足本公司需求变动的能力/重新安排或取消/以及对数量变化的忍受程度；',
    colTwoField: '',
    score: '45',
    scoreMax: 45,
    scoreMin: 0,
    scoreField: 'cooperationScore'
  },
  {
    id: '3',
    colOne: '3.合作情况',
    colTwo: '-采购成本：在同类产品/服务中是否有价格优势；',
    colTwoField: '',
    score: '45',
    scoreMax: 45,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '3',
    colOne: '3.合作情况',
    colTwo: '-交易账期：付款比例及账期时长；',
    colTwoField: '',
    score: '45',
    scoreMax: 45,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '3',
    colOne: '3.合作情况',
    colTwo: '-执行情况：执行效率、履约符合度；',
    colTwoField: '',
    score: '45',
    scoreMax: 45,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '3',
    colOne: '3.合作情况',
    colTwo:
      '-合作意愿：是否愿意投入足够的资源（如人员保障、备库存等）来维护和发展合作关系。',
    colTwoField: '',
    score: '45',
    scoreMax: 45,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '4',
    colOne: '4.服务配合',
    colTwo:
      '-售前服务：提供相应的技术支持和信息支持；组建专门的服务团队并指定相应的负责人；对突发性或临时性需求的快速响应及相应产品与服务的迅速到位；',
    colTwoField: '',
    score: '15',
    scoreMax: 15,
    scoreMin: 0,
    scoreField: 'serviceScore'
  },
  {
    id: '4',
    colOne: '4.服务配合',
    colTwo:
      '-物流服务：交付产品整个过程所能提供的相关物流服务（货物及时发货、货物准确送达、货物完好送达、运输信息及时反馈、客户投诉率及投诉处理时效、回单返回及时率等）；',
    colTwoField: '',
    score: '15',
    scoreMax: 15,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '4',
    colOne: '4.服务配合',
    colTwo: '-售后服务：解决问题的及时性、相应程度及满意度。',
    colTwoField: '',
    score: '15',
    scoreMax: 15,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '5',
    colOne: '5.其他相关要求',
    colTwo:
      '-相关时，是否如约履行合同中规定的信息安全保密及隐私信息保密事宜，无信息安全及隐私泄密。',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: 'otherRequirementsScore'
  },
  {
    id: '5',
    colOne: '5.其他相关要求',
    colTwo:
      '-相关时，所供货品是否满足环保要求及安全要求，是否能够提供相应证据。',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '5',
    colOne: '5.其他相关要求',
    colTwo:
      '-相关时，供应商是否对其环境保护能力及职业健康安全能力进行书面承诺及保证。',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '5',
    colOne: '5.其他相关要求',
    colTwo:
      '-相关时，供应商是否对其环境保护能力及职业健康安全能力进行书面承诺及保证。',
    colTwoField: '',
    score: '10',
    scoreMax: 10,
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '（需写明加、减分的事项和原因）',
    colTwoField: '',
    score: '+/-',
    scoreMax: '0',
    scoreMin: 0,
    scoreField: ''
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '如内部不良评价情况；',
    colTwoField: 'badEvaluationReason',
    score: '2',
    scoreMax: 2,
    scoreMin: -2,
    scoreField: 'badEvaluationScore'
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '如征信预警信息情况（有预警风险减分）',
    colTwoField: 'warningInformationReason',
    score: '2',
    scoreMax: 2,
    scoreMin: -2,
    scoreField: 'warningInformationScore'
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '如客户征信评分（低于590分减分）',
    colTwoField: 'creditRatingReason',
    score: '2',
    scoreMax: 2,
    scoreMin: -2,
    scoreField: 'creditRatingScore'
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '如良好的合作诚意；',
    colTwoField: 'cooperationSincerityReason',
    score: '2',
    scoreMax: 2,
    scoreMin: -2,
    scoreField: 'cooperationSincerityScore'
  },
  {
    id: '6',
    colOne: '6.其他加、减分',
    colTwo: '作为战略型、重要型供应商的酌情加分；',
    colTwoField: 'significantSupplierReason',
    score: '2',
    scoreMax: 2,
    scoreMin: -2,
    scoreField: 'significantSupplierScore'
  }
])

// 表格合并数据
const spanArr = ref([])
/** getSpanArr 获取单元格的合并行数（相同type则进行合并）
spanArr:[]//是一个空的数组，用于存放每一行记录的合并数；
pos:0 //pos是spanArr的索引
 * 1.如果是第一条记录（索引为0），向数组中加入１，并设置索引位置；
 * 2.如果不是第一条记录，则判断它与前一条记录是否相等，
 * 3.如果相等，则向spanArr中添入元素0，并将前一位元素＋１，表示合并行数＋１，
以此往复，得到所有行的合并数，0即表示该行不显示
 * @param {*} data  table列表的数据
  * @param {*} type 字段
 */
const getSpanArr = data => {
  let newSumIndex = [],
    pos = 0
  if (!data) {
    return
  }
  // data就是我们从后台拿到的数据
  for (var i = 0; i < data.length; i++) {
    if (i === 0) {
      // 第一行不处理
      spanArr.value.push(1)
      pos = 0
      newSumIndex.push(i)
    } else {
      // 判断当前元素与上一个元素是否相同
      if (data[i].colOne == data[i - 1].colOne) {
        spanArr.value[pos] += 1 // 首条相同名称行合并行数增加
        spanArr.value.push(0) // 当前行消除
      } else {
        newSumIndex.push(i)
        spanArr.value.push(1)
        pos = i
      }
    }
  }
}
/**objectSpanMethod
 *合并单元格
 * @param {*} param0
 * @param {*} SpanMethodProps
 */
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    // 评分指标 自评得分
    const _row = spanArr.value[rowIndex] //合并行数
    const _col = _row > 0 ? 1 : 0 // 合并列数，1：不改变，0：被消除
    return {
      rowspan: _row,
      colspan: _col
    }
  }
  if ((columnIndex === 3 || columnIndex === 2) && row.id != '6') {
    // 评分指标 自评得分
    const _row = spanArr.value[rowIndex] //合并行数
    const _col = _row > 0 ? 1 : 0 // 合并列数，1：不改变，0：被消除
    return {
      rowspan: _row,
      colspan: _col
    }
  }
}
/** getSummaries
 * 综合得分：
 * @param {*} param
 */
const scoreVal = ref('')
const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  let sum = 0
  const values = data.map(item => Number(formData.value[item.scoreField]))
  values.forEach((value, index) => {
    if (isNaN(value)) return
    sum += value
  })
  columns.forEach((column, index) => {
    if (index === 2) {
      sums[index] = '综合得分：'
      return
    }
    if (index === 3) {
      sums[index] = sum
      scoreVal.value = sum
    }
  })
  return sums
}

const scoreRes = computed(() => {
  let res = '结果'
  switch (true) {
    case scoreVal.value >= 90:
      res = '优秀'
      break
    case 80 <= scoreVal.value && scoreVal.value < 90:
      res = '良好'
      break
    case 60 <= scoreVal.value && scoreVal.value < 80:
      res = '合格'
      break

    default:
      res = '不合格'
      break
  }
  return res
})

// 获取表单基础信息
async function getSupplierData(id) {
  loading.value = true
  let res = await getSupplier(id)
  if (res.code !== 200) return
  let resData = {}
  resData = {
    ...res.data,
    supplierId: res.data.id,
    supplierType: '',
    cooperationMatters: '',
    id: ''
  }
  formData.value = resData
  loading.value = false
}
// 获取表单信息
async function getFormData(id) {
  loading.value = true
  let res = await getEvaluate(id)
  if (res.code !== 200) return
  let resData = {}
  resData = res.data
  formData.value = resData
  loading.value = false
}

// 保存
function handleSubmit(type) {
  return new Promise((resolve, reject) => {
    proxy.$refs.form.validate(async (valid, msg) => {
      if (valid) {
        await saveForm(type, resolve(), reject())
      } else {
        skipToError()
      }
    })
  })
}
// 保存表单
async function saveForm(type, resolve, reject) {
  resolve = resolve ? resolve() : () => {}
  reject = reject ? reject() : () => {}
  let res = await setEvaluate(formData.value)
  if (res.code !== 200) {
    reject(res)
    return
  }
  resolve(res)
  await getFormData(res.data.id)
  // 审批流程id赋值
  examineParam.value.businessId = res.data.id
  if (type == 'examine') {
    handleExamine()
  } else if (type == 'save') {
    proxy.useReturn(
      '',
      () => {
        //返回上一步
        handleReturn()
      },
      async () => {
        //继续
      }
    )
  }
}
// 流程同意调用的方法
async function handleSave() {
  if (!formDisabled.value) {
    return await handleSubmit()
  }
}

const uploadType = {
  contract: ['.rar', '.zip', '.doc', '.docx', '.pdf', '.jpg', '.png', '.jpeg']
}
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile, group) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType['contract'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType['contract']
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传附件
function requestFile(params, group) {
  formData.value[group] = strToArr(formData.value[group])
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      console.log('formData.value==>', formData.value)
      formData.value[group].push(res.data)
      console.log('formData.value[group]==>', formData.value[group])
    }
  })
}
// 删除附件
async function delFileName(index, group) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // let fule = {
      //   // bucketName: 'article',
      //   fileName: formData.value[group][index].fileName
      // }
      const res = await delFile(formData.value[group][index].fileName)
      if (res.code === 200) {
        formData.value[group].splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

const examineParam = ref({}) // 传递的参数
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情
const bpmnStatus = ref('') //表单标题
const formDisabled = ref(false) // 禁用表单
const fieldDisabled = ref([]) // 禁用字段
const fieldHidden = ref([]) // 隐藏字段
/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
 发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13 销售14
/**
 * 提交审批 按钮
 */
const handleExamine = async () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = `${formData.value.supplierName}年度评价` //标题
  examineParam.value.categoryCode = '29' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.type = Number(formData.value.type) //判断供应商来源
  examineParam.value.initiateParams = {
    type: Number(formData.value.type) //判断供应商来源
  }
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: formData.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('29')
  } else {
    isCanStart.value = false
  }
  // if (statusRes.data.status) {
  //   // status判断流程环节05表示结束
  //   isCanStart.value = true
  // } else {
  //   isCanStart.value = false
  // }
}
/***************************业务流程 模块 end****************************************************************/

// 初始化
function init() {
  getSpanArr(tableData.value)
}

init()
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}
//暴露出保存方法
defineExpose({ handleSave })
</script>
<style scoped>
.form-box :deep(.w-full) {
  width: 100%;
}
/* .order-form :deep(.avue-crud__menu) {
  border-bottom: 1px solid #eee;
} */
.form-box .el-collapse {
  border-top: none;
}
.form-box:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

:deep(.avue-crud__empty) {
  padding: 0;
}
</style>

<style lang="scss" scoped>
.tatle-box {
  padding: 20px;
  table {
    @apply border-collapse w-full;
    td {
      @apply border border-solid border-gray-300 p-2;
      box-sizing: border-box;
    }
  }
}
</style>
